<script lang="ts" setup>
import { menuModel } from '@/api/system/menu';
import { useRequest } from '@/hooks/useRequest';
import { cloneDeep } from 'lodash-es';
import { computed, ref, unref } from 'vue';

const { data } = useRequest(menuModel.records, {
  defaultParmas: [{ pageNum: 1, pageSize: 99999 }]
});

const emits = defineEmits(['selected']);

const options = computed(() => {
  const currentData = cloneDeep(unref(data)?.list) || [];
  if(!currentData.length) {return [];}
  const map = {};
  const targetData = [];
  for(const item of unref(currentData)) {
    if(!map[item.id]) {
      map[item.id] = item;
    }
    if(item.parentId === -1) {
      targetData.push(item);
    } else {
      if(map[item.parentId]) {
        if(!map[item.parentId].children) {
          map[item.parentId].children = [];
        }
        map[item.parentId].children.push(item);
      }
    }
  }
  return targetData;
});

const selectedData = defineModel<string>('value');
console.log('selectedData==>', selectedData);

const selected = computed(() => {
  return selectedData.value ? selectedData.value?.split(',').map((item) => +item) : [];
});

const nTreeSelect = ref();

function onUpdateValue(_value) {
  emits('selected', _value);
}

</script>
<template>
  <NTreeSelect
    ref="nTreeSelect"
    multiple
    cascade
    checkable
    :options="options"
    :value="selected"
    label-field="menuName"
    key-field="id"
    max-tag-count="responsive"
    :on-update:value="onUpdateValue"
  />
</template>
